package com.sservice.service.service.impl;

import com.sservice.banfu.mapper.SalePersonMapper;
import com.sservice.banfu.service.SalePersonService1;
import com.sservice.banfu.vo.SalePersonVo;
import com.sservice.common.Arith;
import com.sservice.common.Constants;
import com.sservice.model.dao.*;
import com.sservice.model.entity.*;
import com.sservice.model.log.PayStatus;
import com.sservice.model.vo.AdvanceReceiptVo;
import com.sservice.model.vo.OrderAdvanceReceiptVo;
import com.sservice.service.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by suweiming on 2017/12/20.
 */

@Service
public class OrderAdvanceReceiptServiceImpl implements IOrderAdvanceReceiptService {

    @Autowired
    private OrderAdvanceReceiptMapper dao;
    @Autowired
    private OtherReceivablesMapper otherMapper;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private PurchaseOrderService purchaseOrderService;
    @Autowired
    private ApplyPayBillMapper applyPayBillMapper;
    @Autowired
    private IApplyPayBillService iApplyPayBillService;
    @Autowired
    private IAdvanceReceiptService advanceReceiptService;
    @Autowired
    private AdvanceReceiptMapper advanceReceiptMapper;
    @Autowired
    private IClienteleAccountService accountService;
    @Autowired
    private IAddressDao addressDao;
    @Autowired
    private IClienteleDao clienteleDao;
    @Autowired
    private UserWxMapper userWxDao;
    @Autowired
    private SalePersonService1 salePersonService1;
    //    @Autowired
//    private IOrderAdvanceReceiptService oarService;
    @Autowired
    private OtherReceivablesService otherReceivablesService;

    @Override
    public int insert(OrderAdvanceReceipt record) {
        return dao.insert(record);
    }

    @Override
    public int insertSelective(OrderAdvanceReceipt record) {
        return dao.insertSelective(record);
    }

    @Override
    public List<OrderAdvanceReceiptVo> selectByAdvanceId(OrderAdvanceReceipt record) {
//        return dao.selectByAdvanceId(record);
        return null;
    }


    /**
     * 销售订单多余付款退款
     *
     * @param order
     * @return true 表示退款成功
     */
    @Transactional
    @Override
    public synchronized boolean returnUnnecessaryOrderMoney(Order order) {
        BigDecimal remain = order.getActualReceived().subtract(order.getActualPrice().multiply(order.getActualNumber()));//
        if (remain.compareTo(BigDecimal.valueOf(0.0)) != 1) {
            return false;
        }
        OrderAdvanceReceipt oar = new OrderAdvanceReceipt();
        oar.setType("0"); // 预收款单
        oar.setOrderId(String.valueOf(order.getId())); //
        List<OrderAdvanceReceipt> list = dao.selectByOrderId(oar);
        for (int i = 0; i < list.size(); i++) {
            OrderAdvanceReceipt oar_ = list.get(i);
            if (oar_.getPayCash().compareTo(remain) == 1 || oar_.getPayCash().compareTo(remain) == 0) {
                AdvanceReceipt ar = advanceReceiptMapper.selectByPrimaryKey(Integer.valueOf(oar_.getAdvanceReceiptId()));
                ar.setTotalVerified(ar.getTotalVerified().subtract(remain));
                ar.setVerifiedOver("0");
                advanceReceiptMapper.updateByPrimaryKey(ar);
                oar_.setPayCash(oar_.getPayCash().subtract(remain));
                dao.updateByPrimaryKeySelective(oar_);
                break;
            } else if (oar_.getPayCash().compareTo(remain) == -1) {
                remain = remain.subtract(oar_.getPayCash());
                AdvanceReceipt ar = advanceReceiptMapper.selectByPrimaryKey(Integer.valueOf(oar_.getAdvanceReceiptId()));
                ar.setTotalVerified(ar.getTotalVerified().subtract(oar_.getPayCash()));
                ar.setVerifiedOver("0");
                advanceReceiptMapper.updateByPrimaryKey(ar);
                oar_.setPayCash(BigDecimal.valueOf(0.0));
                dao.updateByPrimaryKeySelective(oar_);
            }
        }
        return true;
    }


    /**
     * 通过预付款单进行付款
     *
     * @param record
     * @return
     */
    @Transactional
    @Override
    public Object payOrder(OrderAdvanceReceiptVo record) {
        String[] receiptIds = record.getAdvanceReceiptId().split(",");
        String[] ordersId = record.getOrderIdDesc().split(",");
        String[] pay = record.getPayCashDesc().split(",");
        String[] actualTotal = record.getActualTotalDesc().split(","); //
        double total = 0; //付款合计
        List<AdvanceReceipt> list = new ArrayList<AdvanceReceipt>();
        List orders = new ArrayList<Order>();
        List oarList = new ArrayList<OrderAdvanceReceipt>(); //付款
        int pointer = 0; // 预付款指针
        for (int i = 0; i < ordersId.length; i++) {
            Order order = new Order();
            OrderAdvanceReceipt oar = new OrderAdvanceReceipt();
            order.setId(Integer.valueOf(ordersId[i]));
            order.setActualReceived(BigDecimal.valueOf(Double.valueOf(actualTotal[i])));
            oar.setOrderId(ordersId[i]);
            BigDecimal arSingleTotal = BigDecimal.valueOf(Double.valueOf(pay[pointer]));
            if (order.getActualReceived().compareTo(arSingleTotal) == 0) { // 等于
                oar.setOrderId(ordersId[i]); //
                oar.setPayCash(order.getActualReceived()); //
                oar.setOperator(record.getOperator()); //
                oar.setAdvanceReceiptId(receiptIds[pointer]); //
                oar.setRemark(record.getRemark());
                oarList.add(oar);
                pointer++;
                // 付款 //
            } else if (order.getActualReceived().compareTo(arSingleTotal) == -1) { // 小于
                oar.setOrderId(ordersId[i]); //
                oar.setPayCash(order.getActualReceived()); //
                oar.setOperator(record.getOperator()); //
                oar.setAdvanceReceiptId(receiptIds[pointer]); //
                oar.setRemark(record.getRemark());
                oarList.add(oar);
                pay[pointer] = String.valueOf(arSingleTotal.subtract(order.getActualReceived()));
            } else if (order.getActualTotal().compareTo(arSingleTotal) == 1) { // 大于
                int next = getNextSatisfied(pay, order.getActualReceived().subtract(arSingleTotal), pointer); //获取下一个满足当前订单余额的指针
                BigDecimal total_ = order.getActualReceived().subtract(arSingleTotal);
                for (int j = pointer; j < next; j++) { //
                    OrderAdvanceReceipt oar1 = new OrderAdvanceReceipt();
                    oar1.setOrderId(ordersId[j]); //
                    oar1.setPayCash(BigDecimal.valueOf(Double.valueOf(pay[j]))); //
                    oar1.setOperator(record.getOperator()); //
                    total_ = total_.subtract(BigDecimal.valueOf(Double.valueOf(pay[j]))); // 从余额中扣减
                    oar1.setAdvanceReceiptId(receiptIds[j]); //
                    oar1.setRemark(record.getRemark());
                    oarList.add(oar1);
                }
                pointer = next;
                pay[pointer] = String.valueOf(BigDecimal.valueOf(Double.valueOf(pay[next])).subtract(total_));
                oar.setOrderId(ordersId[i]); //
                oar.setPayCash(total_); //
                oar.setOperator(record.getOperator()); //
                oar.setAdvanceReceiptId(receiptIds[pointer]); //
                oar.setRemark(record.getRemark());
                oarList.add(oar);
            }
            Order order_ = orderService.selectByPrimaryKey(order.getId());
            order.setActualReceived(order_.getActualReceived().add(order.getActualReceived()));

            if (order.getActualReceived().equals(order_.getActualTotal())) { //付款完成
                order.setPayStatus("1"); //付款完成
            } else if (order_.getActualReceived().compareTo(BigDecimal.valueOf(0.0)) == 0 && order.getActualReceived().compareTo(BigDecimal.valueOf(0.0)) == 1) {
                order.setPayStatus("2"); //付款中
            } else if (order.getActualReceived().compareTo(order_.getActualTotal()) == 1) {
                throw new Error("订单累计付款金额超出订单金额,拒绝付款!");
            } else {
                order.setPayStatus("2");
            }
            orders.add(order); //
        }
        // 预付款单中扣除 核销
        for (int i = 0; i < receiptIds.length; i++) {
            total = Arith.add(total, Double.valueOf(pay[i]));
            AdvanceReceipt ar = advanceReceiptService.selectByPrimaryKey(Integer.valueOf(receiptIds[i]));
            AdvanceReceipt ar1 = new AdvanceReceipt();
            ar1.setId(Integer.valueOf(receiptIds[i]));
            ar1.setTotalVerified(BigDecimal.valueOf(Double.valueOf(pay[i])).add(ar.getTotalVerified()));
            if (ar.getTotalDeposit().equals(ar1.getTotalVerified())) {
                ar1.setVerifiedOver("1"); //核销
            } else {
                ar1.setVerifiedOver("0"); //核销
            }
            list.add(ar1);
        }
        int res = dao.payInBatch(oarList); // 插入 // 批量付款
        if (res != oarList.size()) {
            throw new RuntimeException("付款错误回滚!");
        }
        int res_update_in_batch = advanceReceiptService.updateAdvanceReceiptInBatch(list);
        if (res_update_in_batch != list.size()) {
            throw new RuntimeException("错误回滚!");
        }

        int res_order_update = orderService.payOrderInBatch(orders);
        if (res_order_update == 0) {
            throw new RuntimeException("订单错误回滚!");
        }

        /// 从客户账户余额中扣除
        ClienteleAccount ca = accountService.selectClientAccountByClientele(record.getClienteleId());
        ca.setYushouRemain(ca.getYushouRemain().subtract(BigDecimal.valueOf(record.getTotal())));
        int res_ca = accountService.updateByPrimaryKeySelective(ca);
        if (res_ca == 0) {
            throw new RuntimeException("客户账户更新错误回滚!");
        }
        return res_order_update;
    }

    /***
     *  核算锁定
     * @param record
     * @return
     */
    @Override
    public Object lockAdvanceBill(OrderAdvanceReceiptVo record, int locker) {
        // 更新采购订单核算状态
        ApplyPayBill po = applyPayBillMapper.selectByPrimaryKey(Integer.valueOf(record.getOrderIdDesc()));
        if (!po.getStatusHesuan().equals("0")) {
            return "操作非法!";
        }
        String[] ordersId = record.getOrderIdDesc().split(",");
        if (record.getAdvanceReceiptId() != null) {
            String[] receiptIds = record.getAdvanceReceiptId().split(","); // 预付款单
            String[] pay = record.getPayCashDesc().split(","); //预付款金额
            List<AdvanceReceipt> list = new ArrayList<AdvanceReceipt>();
            for (int i = 0; i < receiptIds.length; i++) {
                AdvanceReceipt ar = new AdvanceReceipt();
                ar.setId(Integer.valueOf(receiptIds[i]));
                ar.setLocked("1");
                ar.setLockTotal(BigDecimal.valueOf(Double.valueOf(pay[i])));
                ar.setLockForOther("0");// 不是其他应付款的锁定
                ar.setLocker(String.valueOf(locker));
                ar.setLockTime(new Date());
                ar.setLockOrderId(ordersId[0]);
                list.add(ar);
            }
            int res_update_in_batch = advanceReceiptService.lockAdvanceReceiptInBatch(list);
            if (res_update_in_batch != list.size()) {
                throw new RuntimeException("错误回滚!");
            }
        }
        ApplyPayBill po1 = new ApplyPayBill();
        po1.setStatusHesuan("1");
        po1.setId(po.getId());
        po1.setNeedPayTotal(BigDecimal.valueOf(record.getCashTotal()));
        po1.setUserHesuan(record.getClienteleId());
        po1.setUserName(getUserName(1, record.getUserName(), po.getUserName()));
        int res = applyPayBillMapper.updateByPrimaryKeySelective(po1);
        return ordersId[0];
    }

    private String getUserName(int place, String userName, String origin) {
        if (origin == null) {
            origin = ":::";
        }
        String[] users = origin.split(":");
        String[] use_ = new String[4];
        for (int i = 0; i < users.length; i++) {
            if (place == i) {
                use_[i] = userName;
            } else {
                use_[i] = users[i];
            }
        }
        return String.join(":", use_);
    }


    @Transactional
    @Override
    public Object check(AdvanceReceiptVo record) {
        ApplyPayBill po = applyPayBillMapper.selectByPrimaryKey(Integer.valueOf(record.getOrderId()));
        if (po.getStatusHesuan().equals("1") && (po.getStatusCheck().equals("0") || po.getStatusCheck().equals("2"))) { // 核算状态已核算，审核状态未审核时才允许继续
        } else {
            return "操作非法";
        }
        if (record.getRemark().equals("2")) { // 核算审核拒绝
            AdvanceReceiptVo arv = new AdvanceReceiptVo();
            arv.setLockOrderId(record.getOrderId());
            arv.setType("2"); // 预付款单
            arv.setClienteleId(po.getClienteleId());
            advanceReceiptService.releaseLockedAdvanceBill(arv); // 解除锁定
            ApplyPayBill po1 = new ApplyPayBill();
            po1.setId(po.getId());
            if ("2".equals(record.getRemark())) {
                po1.setStatusHesuan("0");///
            }
            po1.setStatusCheck(record.getRemark());
            po1.setUserCheck(record.getClienteleId());
            po1.setUserName(getUserName(2, record.getUserName(), po.getUserName()));
            return applyPayBillMapper.updateByPrimaryKeySelective(po1);
        } else { // 审核通过
            ApplyPayBill po1 = new ApplyPayBill();
            po1.setStatusCheck(record.getRemark());
            po1.setId(po.getId());
            po1.setUserCheck(record.getClienteleId());
            po1.setUserName(getUserName(2, record.getUserName(), po.getUserName()));
            // 审核用户
            return applyPayBillMapper.updateByPrimaryKeySelective(po1);
        }

    }

    /**
     * 采购财务付款
     *
     * @param record
     * @return
     */
    @Transactional
    @Override
    public Object pay(AdvanceReceiptVo record) {
        ApplyPayBill po = applyPayBillMapper.selectByPrimaryKey(Integer.valueOf(record.getOrderId()));
        if (!po.getStatusHesuan().equals("1") || !po.getStatusCheck().equals("1")) {
            return "操作非法";
        }
        AdvanceReceiptVo arv = new AdvanceReceiptVo();
        arv.setClienteleId(po.getClienteleId());
        arv.setUnitCode(po.getUnitCode());
        arv.setType("2");
        arv.setVerifiedOver("!1");
        arv.setLocked("1");
        List<AdvanceReceiptVo> list = advanceReceiptService.queryByClienteleId(arv);
        String ids = record.getLocked();
        if (list.size() > 0) {
            List<AdvanceReceipt> list1 = new ArrayList();
            List<OrderAdvanceReceipt> listOar = new ArrayList<OrderAdvanceReceipt>();
            BigDecimal total = BigDecimal.valueOf(0.0);
            for (AdvanceReceiptVo arvo : list) {
                OrderAdvanceReceipt oar = new OrderAdvanceReceipt();
                AdvanceReceipt arv1 = new AdvanceReceipt();
                arv1.setId(arvo.getId());
                oar.setPayCash(arvo.getLockTotal());
                total = total.add(arvo.getLockTotal());
                oar.setOrderId(record.getOrderId());
                oar.setRemark("审核付款");
                oar.setAdvanceReceiptId(String.valueOf(arvo.getId()));
                oar.setOperator(record.getOperator());
                oar.setOrderNo(arvo.getNo());
                arv1.setLocked("0");
                arv1.setTotalVerified(arvo.getLockTotal().add(arvo.getTotalVerified()));
                if (arv1.getTotalVerified().compareTo(arvo.getTotalDeposit()) == 0) {
                    arv1.setVerifiedOver("1");
                } else {
                    arv1.setVerifiedOver("0");
                }
                oar.setGoodsId(po.getGoodsId());
                oar.setType("1"); //预付款单
                list1.add(arv1);
                listOar.add(oar);
            }
            dao.payInBatch(listOar);
            AdvanceReceiptVo arv1 = new AdvanceReceiptVo();
            arv1.setList(list1);
            arv1.setLockOrderId(record.getOrderId()); // 付款申请
            advanceReceiptMapper.payByLockedInBatch(arv1);
        }
        ApplyPayBill po1 = new ApplyPayBill();
        po1.setId(po.getId());
        po1.setStatusPay("1"); // 核算付款
        po1.setActual(po.getTotal()); // 实际收款
        po1.setUserName(getUserName(3, record.getUserName(), po.getUserName()));
        po1.setUserPay(record.getOperator());
        if (po.getType().equals("0")) { // 采购付款申请单
            PurchaseOrder po2 = purchaseOrderService.selectByPrimaryKey(Integer.valueOf(po.getOrderId()));
            PurchaseOrder po3 = new PurchaseOrder();
            po3.setId(po2.getId());
            po3.setActualReceiveTotal(po2.getActualReceiveTotal().add(po.getTotal()));
            if (po3.getActualReceiveTotal().compareTo(po2.getTotal()) == 0) {
                po3.setPayStatus(PayStatus.ED.getIndex());
            } else {
                po3.setPayStatus(PayStatus.PART.getIndex());
            }
            po3.setApplyPayTotal(po2.getApplyPayTotal().subtract(po.getTotal())); // 扣减申请金额
            purchaseOrderService.updateByPrimaryKeySelective(po3);
        } else if (po.getType().equals("1")) {
            Order po2 = orderService.selectByPrimaryKey(Integer.valueOf(po.getOrderId()));
            Order po3 = new Order();
            po3.setApplyBack("3"); // 完全退款
            po3.setId(po2.getId());
            orderService.updateByPrimaryKeySelective(po3);
        }
        return applyPayBillMapper.updateByPrimaryKeySelective(po1);
    }

    /**
     * 财务退款
     *
     * @param record.orderId 必穿参数
     * @return
     */
    public Object reback(AdvanceReceiptVo record) {
        ApplyPayBill po = applyPayBillMapper.selectByPrimaryKey(Integer.valueOf(record.getOrderId()));
        if (!po.getStatusHesuan().equals("1")
                || !po.getStatusCheck().equals("1")
                || !po.getStatusPay().equals("1")
                || po.getActual().compareTo(BigDecimal.ZERO) <= 0
                || po.getActual().compareTo(po.getTotal()) == 1) {
            throw new RuntimeException("付款申请单未付款或数据非法，不能进行退款");
        }
        if (po.getNeedPayTotal().compareTo(BigDecimal.ZERO) == 1) { // 包含银行付款的
            if (record.getType().equals("1")) {
                record.setTotalDeposit(po.getNeedPayTotal());
                record.setClienteleId(po.getClienteleId());
                record.setUnitCode(po.getUnitCode());
                record.setType("2"); // 转换
                advanceReceiptService.createAdvancePay(record); // 银行付款转化为预付款单
            }
        }
        OrderAdvanceReceipt oar = new OrderAdvanceReceipt();
        oar.setOrderId(record.getOrderId());
        oar.setType("1");
        List<OrderAdvanceReceipt> list = dao.selectByOrderId(oar);
        for (OrderAdvanceReceipt oar1 : list) {
            advanceReceiptService.changeNumber(
                    Integer.valueOf(oar1.getAdvanceReceiptId()),
                    oar1.getPayCash().negate()
            );
            iApplyPayBillService.changeNumber(Integer.valueOf(oar1.getOrderId()),
                    oar1.getPayCash().negate());
            dao.deleteByPrimaryKey(oar1.getId());//#
        }
        purchaseOrderService.changeMoney(Integer.valueOf(po.getOrderId()), po.getTotal(),
                po.getActual().negate());

        ApplyPayBill apb = new ApplyPayBill();
        apb.setId(po.getId());
        apb.setNeedPayTotal(BigDecimal.ZERO);
        apb.setActual(BigDecimal.ZERO);
        apb.setStatusHesuan("0");
        apb.setStatusPay("0");
        apb.setStatusCheck("0");
        return applyPayBillMapper.updateByPrimaryKeySelective(apb);
        //return iApplyPayBillService.changeNumber(po.getId(), BigDecimal.ZERO); //
    }

    private int getNextSatisfied(String[] payCash, BigDecimal total, int pointer) {
        int next = 0;
        return getNext(next, pointer, payCash, total);
    }

    @Override
    public int getNext(int next, int pointer, String[] payCash, BigDecimal total) {
        BigDecimal totalTmp = BigDecimal.valueOf(0.0);

        for (int i = pointer; i < payCash.length; i++) {
            totalTmp = totalTmp.add(BigDecimal.valueOf(Double.valueOf(payCash[i])));
            if (totalTmp.compareTo(total) == 0) {
                next = i++;
                break;
            } else if (totalTmp.compareTo(total) == -1) {
                continue;
            } else if (totalTmp.compareTo(total) == 1) {
                next = i;
                break;
            }
        }
        return next;
    }

    @Transactional
    @Override
    public Object otherLockAdvanceBill(OrderAdvanceReceiptVo record, int locker) {
        // 更新其他付款核算状态
        OtherReceivables po = otherMapper.selectByPrimaryKey(Integer.valueOf(record.getOrderIdDesc()));
        if (!po.getStatusHesuan().equals("0")) {
            return "操作非法!";
        }
        String[] ordersId = record.getOrderIdDesc().split(",");
        if (record.getAdvanceReceiptId() != null) {
            String[] receiptIds = record.getAdvanceReceiptId().split(","); // 预付款单
            String[] pay = record.getPayCashDesc().split(","); //预付款金额
            List<AdvanceReceipt> list = new ArrayList<AdvanceReceipt>();
            for (int i = 0; i < receiptIds.length; i++) {
                AdvanceReceipt ar = new AdvanceReceipt();
                ar.setId(Integer.valueOf(receiptIds[i]));
                ar.setLocked("1");
                ar.setLockForOther("1"); // 其他应付款的锁定
                ar.setLockTotal(BigDecimal.valueOf(Double.valueOf(pay[i])));
                ar.setLocker(String.valueOf(locker));
                ar.setLockTime(new Date());
                ar.setLockOrderId(ordersId[0]);
                list.add(ar);
            }
            int res_update_in_batch = advanceReceiptService.lockAdvanceReceiptInBatch(list);
            if (res_update_in_batch != list.size()) {
                throw new RuntimeException("错误回滚!");
            }
        }
        OtherReceivables po1 = new OtherReceivables();
        po1.setStatusHesuan("1");
        po1.setId(po.getId());
        po1.setNeedPayCash(BigDecimal.valueOf(record.getCashTotal()));
        po1.setUserHesuan(record.getClienteleId());
        po1.setUserName(getUserName(1, record.getUserName(), po.getUserName()));
        int res = otherMapper.updateByPrimaryKeySelective(po1);
        return res;
    }

    @Transactional
    @Override
    public Object otherCheck(AdvanceReceiptVo record) {
        OtherReceivables po = otherMapper.selectByPrimaryKey(Integer.valueOf(record.getOrderId()));
        if (po.getStatusHesuan().equals("1") && (po.getStatusCheck().equals("0") || po.getStatusCheck().equals("2"))) { // 核算状态已核算，审核状态未审核时才允许继续

        } else {
            return "操作非法";
        }
        if (record.getRemark().equals("2")) { // 核算审核拒绝
            AdvanceReceiptVo arv = new AdvanceReceiptVo();
            arv.setLockOrderId(record.getOrderId());
            arv.setType("2"); // 预付款单
            arv.setClienteleId(po.getClienteleId());
            int release = advanceReceiptService.releaseLockedAdvanceBill(arv);
            OtherReceivables po1 = new OtherReceivables();
            po1.setId(po.getId());
            if ("2".equals(record.getRemark())) {
                po1.setStatusHesuan("0");///
            }
            po1.setStatusCheck(record.getRemark());
            po1.setUserCheck(record.getClienteleId());
            po1.setUserName(getUserName(2, record.getUserName(), po.getUserName()));
            return otherMapper.updateByPrimaryKeySelective(po1);
        } else { // 审核通过
            OtherReceivables po1 = new OtherReceivables();
            po1.setStatusCheck(record.getRemark());
            po1.setId(po.getId());
            po1.setUserCheck(record.getClienteleId());
            po1.setUserName(getUserName(2, record.getUserName(), po.getUserName()));
            // 审核用户
            return otherMapper.updateByPrimaryKeySelective(po1);
        }

    }


    @Transactional
    @Override
    public Object otherPay(AdvanceReceiptVo record) {
        OtherReceivables po = otherMapper.selectByPrimaryKey(Integer.valueOf(record.getOrderId()));
        if (!po.getStatusHesuan().equals("1") || !po.getStatusCheck().equals("1")) {
            return "操作非法";
        }
        AdvanceReceiptVo arv = new AdvanceReceiptVo();
        arv.setClienteleId(po.getClienteleId());
        arv.setUnitCode(po.getUnitCode());
        arv.setType("2");
        arv.setVerifiedOver("!1");
        arv.setLocked("1");
        arv.setLockForOther("1");
        List<AdvanceReceiptVo> list = advanceReceiptService.queryByClienteleId(arv);
        String ids = record.getLocked();
        if (list.size() > 0) {
            List<AdvanceReceipt> list1 = new ArrayList();
            List<OrderAdvanceReceipt> listOar = new ArrayList<OrderAdvanceReceipt>();
            BigDecimal total = BigDecimal.valueOf(0.0);
            for (AdvanceReceiptVo arvo : list) {
                OrderAdvanceReceipt oar = new OrderAdvanceReceipt();
                AdvanceReceipt arv1 = new AdvanceReceipt();
                arv1.setId(arvo.getId());
                oar.setPayCash(arvo.getLockTotal());
                total = total.add(arvo.getLockTotal());
                oar.setOrderId(record.getOrderId());
                oar.setRemark("审核付款");
                oar.setIsOther("1");
                oar.setAdvanceReceiptId(String.valueOf(arvo.getId()));
                oar.setOperator(record.getOperator());
                oar.setOrderNo(arvo.getNo());
                arv1.setLocked("0");
                arv1.setLockForOther("1");
                arv1.setTotalVerified(arvo.getLockTotal().add(arvo.getTotalVerified()));
                if (arv1.getTotalVerified().compareTo(arvo.getTotalDeposit()) == 0) {
                    arv1.setVerifiedOver("1");
                } else {
                    arv1.setVerifiedOver("0");
                }
                oar.setType("1"); //预付款单
                advanceReceiptMapper.updateByPrimaryKeySelective(arv1);
                listOar.add(oar);
            }
            dao.payInBatch(listOar);
//            advanceReceiptMapper.payByLockedInBatch(list1);
        }
        OtherReceivables po1 = new OtherReceivables();
        po1.setId(po.getId());
        po1.setStatusPay("1"); // 核算付款
        po1.setAccountReceivables(po.getReceivables());
        po1.setUserName(getUserName(3, record.getUserName(), po.getUserName()));
        po1.setUserPay(record.getOperator());
        return otherMapper.updateByPrimaryKeySelective(po1);
    }

    @Override
    public int payInBatch(List<OrderAdvanceReceipt> record) {
        return dao.payInBatch(record);
    }

    @Override
    public int payInBatchOtherOrder(List<OrderAdvanceReceipt> record) {
        return dao.payInBatchOtherOrder(record);
    }

    private Map payOrder(String[] receiptIds, String[] pay, String[] goodsId, String[] orderNo, OrderAdvanceReceiptVo record) {
        double total = 0; //付款合计
        List<AdvanceReceipt> list = new ArrayList<AdvanceReceipt>();
        //  预付款
        List<OrderAdvanceReceipt> list_oar = new ArrayList<OrderAdvanceReceipt>();
        int pointer = 0;
        for (int i = 0; i < receiptIds.length; i++) {
            OrderAdvanceReceipt oar = new OrderAdvanceReceipt();
            oar.setOperator(record.getOperator());
            oar.setOrderId(record.getOrderId());
            total = Arith.add(total, Double.valueOf(pay[i]));
            oar.setPayCash(BigDecimal.valueOf(Double.valueOf(pay[i])));
            oar.setAdvanceReceiptId(receiptIds[i]);
            oar.setRemark(record.getRemark());
            if (goodsId.length > 0) {
                oar.setGoodsId(goodsId[0]);
                oar.setOrderNo(orderNo[0]);
            }
            oar.setType("0");
            list_oar.add(oar);
            AdvanceReceipt ar = advanceReceiptService.selectByPrimaryKey(Integer.valueOf(receiptIds[i]));
            AdvanceReceipt ar1 = new AdvanceReceipt();

            ar1.setId(Integer.valueOf(receiptIds[i]));

            ar1.setTotalVerified(BigDecimal.valueOf(Double.valueOf(pay[i])).add(ar.getTotalVerified()));
            if (ar.getTotalDeposit().equals(ar1.getTotalVerified())) {
                ar1.setVerifiedOver("1"); //核销
            } else {
                ar1.setVerifiedOver("0"); //核销
            }
            list.add(ar1);
        }

        int res = 0; // 插入 // 批量付款
        if (goodsId.length == 0) {
            res = dao.payInBatchOtherOrder(list_oar);
        } else {
            res = dao.payInBatch(list_oar);
        }
        Map map = new HashMap<String, Object>();
        map.put("inBatch", res);
        map.put("list", list);
        map.put("total", total);
        return map;
    }

    /***
     * @param record
     * @return
     */
    @Transactional
    @Override
    public Object payByAdvanceReceipt(OrderAdvanceReceiptVo record) {

        String[] receiptIds = record.getAdvanceReceiptId().split(",");

        String[] pay = record.getPayCashDesc().split(",");
        String[] goodsId = new String[0];
        if (record.getOrderNoDesc() != null) {
            goodsId = record.getGoodsIdDesc().split(",");
        }
        String[] orderNo = new String[0];
        if (record.getOrderNoDesc() != null) {
            orderNo = record.getOrderNoDesc().split(",");
        }
        List<OrderAdvanceReceipt> list_oar = new ArrayList<OrderAdvanceReceipt>();

        Map map = payOrder(receiptIds, pay, goodsId, orderNo, record);
        int res = (int) map.get("inBatch"); // 插入 // 批量付款
        List<AdvanceReceipt> list = (List<AdvanceReceipt>) map.get("list"); // 插入 // 批量付款

        if (res != receiptIds.length) {
            throw new Error("付款错误回滚!");
        }
        int res_update_in_batch = advanceReceiptService.updateAdvanceReceiptInBatch(list);
        if (res_update_in_batch != list.size()) {
            throw new Error("错误回滚!");
        }
        BigDecimal total = BigDecimal.valueOf((double) map.get("total"));
        if (goodsId.length == 0) {
            //其他应收款付款
            OtherReceivables order = otherReceivablesService.selectByPrimaryKey(Integer.valueOf(record.getOrderId()));
            OtherReceivables payed = new OtherReceivables();
            payed.setId(Integer.valueOf(record.getOrderId()));
            payed.setAccountReceivables(order.getAccountReceivables().add(total));
            int res_ = payed.getAccountReceivables().compareTo(order.getReceivables());
            if (res_ == 0) {
                payed.setVerified("1");
            } else if (res_ == 1) {
                throw new RuntimeException("支付金额大于应付款金额");
            }
            int res_payed = otherReceivablesService.updateByPrimaryKeySelective(payed);
            if (res_payed == 0) {
                throw new RuntimeException("订单错误回滚!");
            }
        } else {


            //销售订单付款   ----
            Order order = orderService.selectByPrimaryKey(Integer.valueOf(record.getOrderId()));
            Order payed = new Order();
            payed.setId(order.getId());
            payed.setActualReceived(total.add(order.getActualReceived())); // 实际支付累加
            if (payed.getActualReceived().compareTo(order.getActualTotal()) == 0) { //付款完成
                payed.setPayStatus("1"); //付款完成
            } else if (order.getActualReceived().compareTo(BigDecimal.valueOf(0.0)) == 0
                    && payed.getActualReceived().compareTo(BigDecimal.valueOf(0.0)) == 1) {
                payed.setPayStatus("2"); //付款中
            } else if (payed.getActualReceived().compareTo(order.getActualTotal()) == 1) {
                throw new Error("订单累计付款金额超出订单金额,拒绝付款!");
            }
            int res_order_update = orderService.updateByPrimaryKeySelective(payed);
            if (res_order_update == 0) {
                throw new RuntimeException("订单错误回滚!");
            } else {
                SalePersonVo salepManager = salePersonService1.selectByPrimaryKey(Integer.valueOf(order.getSaleId()));
                if (salepManager.getOpenid() != null) {
                    UserWx uwManager = new UserWx();
                    uwManager.setUnionid(salepManager.getOpenid());
                    uwManager.setUnitid(Constants.WXUserTypeWX);
                    UserWx ux1Manager = userWxDao.selectByUnionid(uwManager);
                    if (ux1Manager != null) {
                        if (order.getAddress() != null) {
                            Address address = addressDao.selectByPrimaryKey(Integer.valueOf(order.getAddress()));
                            // 模板消息
                            orderService.sendPayedTmpMsg("您的订单已完成付款，商家将即时为您发货.", order.getActualTotal(), order.getGoodsName(),
                                    address.getDetail(), order.getNo(), "查看订单详情",
                                    ux1Manager.getOpenid());
                        } else {
                            Clientele clientele = clienteleDao.selectByPrimaryKey(Integer.valueOf(order.getClienteleId()));
                            orderService.sendPayedTmpMsg("您的订单已完成付款，商家将即时为您发货.", order.getActualTotal(), order.getGoodsName(),
                                    clientele.getAddress(), order.getNo(), "查看订单详情",
                                    ux1Manager.getOpenid());
                        }
                    }

                }
            }
        }
        /// 从客户账户余额中扣除
        ClienteleAccount ca = accountService.selectClientAccountByClientele(record.getClienteleId());
        ca.setYushouRemain(ca.getYushouRemain().subtract(total));
        int res_ca = accountService.updateByPrimaryKeySelective(ca);
        if (res_ca == 0) {
            throw new Error("客户账户更新错误回滚!");
        }
        return ca;
    }

    /**
     * 撤销退款，前提是已付款未收款
     *
     * @param order
     * @return
     */
    @Transactional
    @Override
    public Object rebackByOrderAdvanceReceipt(OrderAdvanceReceipt order) {

        List<OrderAdvanceReceipt> list = dao.selectByOrderId(order); // 查询付款单
        if (list.size() == 0 || order.getAdvanceReceiptId() == null) {
            return "参数错误";
        }
        String advanceIds = "," + order.getAdvanceReceiptId() + ",";
        for (OrderAdvanceReceipt oar : list) {
            if (advanceIds.indexOf("," + oar.getId() + ",") > -1) {
                if (oar.getPayCash().equals(BigDecimal.ZERO)) {
                    throw new RuntimeException("订单付款单已经退款");
                }
                if (oar.getPayCash().compareTo(BigDecimal.ZERO) == -1) {
                    throw new RuntimeException("退款金额错误！");
                }
                advanceReceiptService.changeNumber(Integer.valueOf(oar.getAdvanceReceiptId()), oar.getPayCash().negate());
                orderService.changeMoneyNumber(Integer.valueOf(oar.getOrderId()), oar.getPayCash().negate());
                dao.deleteByPrimaryKey(oar.getId());
            }
        }
        return null;
    }


}
